/**
 * @Author Yenchingcheng
 * @Date 2023/5/14 23:37
 * @Description 饿汉式
 **/
public class Singleton01 {

    public static void main(String[] args) {
        System.out.println("饿汉式：");
        //测试Singleton
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        System.out.println(s1 == s2);//返回true
        //测试Singleton1
        Singleton1 s3 = Singleton1.getInstance();
        Singleton1 s4 = Singleton1.getInstance();
        System.out.println(s3.hashCode() == s4.hashCode());//返回true
    }

}

//饿汉式（构造器）
class Singleton {

    //构造器私有化，不能new
    private Singleton() {
    }

    //2.类内部创建静态对象实例
    private final static Singleton instance = new Singleton();

    //3.提供共有的静态方法，返回实例对象
    public static Singleton getInstance() {
        return instance;
    }

}

//饿汉式（静态代码块）
class Singleton1 {

    private Singleton1() {
    }

    private static Singleton1 instance = new Singleton1();

    static {
        instance = new Singleton1();
    }

    public static Singleton1 getInstance() {
        return instance;
    }
}
